package com.zrf.base.knowledge.leetcode.editor.cn;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * //给定一个二叉树，返回它的中序 遍历。
 * //
 * // 示例:
 * //
 * // 输入: [1,null,2,3]
 * //   1
 * //    \
 * //     2
 * //    /
 * //   3
 * //
 * //输出: [1,3,2]
 * //
 * // 进阶: 递归算法很简单，你可以通过迭代算法完成吗？
 * // Related Topics 栈 树 哈希表
 * // 👍 763 👎 0
 *
 * @author zhouruifeng
 * @date 2020-11-03 07:48:24
 */
public class BinaryTreeInorderTraversal {
    public static void main(String[] args) {
        Solution solution = new BinaryTreeInorderTraversal().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> resultList = new ArrayList();

            Stack<TreeNode> stack = new Stack();
            TreeNode treeNode = root;
            while (treeNode != null || !stack.isEmpty()) {
                while (treeNode != null) {
                    stack.push(treeNode);
                    treeNode = treeNode.left;
                }
                treeNode = stack.pop();
                resultList.add(treeNode.val);
                treeNode = treeNode.right;
            }
            return resultList;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}